package com.hxm.demo.newcoder;

import java.util.HashSet;
import java.util.Set;

/**
 * description: add a description
 *
 * @author huangxiaoming
 * @version 1.0.0
 * @date 2023/08/24 17:00:33
 */
public class TestBM7 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = head.next.next;
        ListNode listNode = EntryNodeOfLoop2(head);
        System.out.println(listNode);
    }

    public static ListNode EntryNodeOfLoop1(ListNode pHead) {
        Set<ListNode> set = new HashSet<>();
        while (pHead != null) {
            if (set.contains(pHead)) {
                return pHead;
            }
            set.add(pHead);
            pHead = pHead.next;
        }
        return null;
    }

    public static ListNode EntryNodeOfLoop2(ListNode pHead) {
        ListNode first = pHead;
        ListNode slow = pHead;
        while (first != null && first.next != null) {
            first = first.next.next;
            slow = slow.next;
            if (first == slow) {
                break;
            }
        }
        if (first == null || first.next == null) {
            return null;
        }
        first = pHead;
        while (first != slow) {
            first = first.next;
            slow = slow.next;
        }
        return first;
    }
}
